package com.yx.listener;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.yx.constatns.RabbitMQConstatns;
import com.yx.service.ISearchGoodsService;
import com.yx.vo.Goods;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Classname GoodsESQueueListener
 * @Date 2021/07/12 19:50
 * @Author by yx
 * @Description TODO:
 */
@Component
@Slf4j
public class GoodsESQueueListener {

    @Autowired
    private ISearchGoodsService searchGoodsService;

    @RabbitListener(queues = RabbitMQConstatns.GOODS_QUEUE)
    public void GoodsToES(String json, Channel channel, Message message) throws IOException {
        //1.获取routingkey
        String routingKey = message.getMessageProperties().getReceivedRoutingKey();
        Goods goods = JSON.parseObject(json, Goods.class);

        switch (routingKey) {
            case "shop.goods.insert":
                try {
                    //1.向es插入数据
                    searchGoodsService.addGoods(goods);
                    //手动ack
                    channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
                } catch (IOException e) {
                    log.error("向es添加数据出现了异常", e);
                    channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
                }
                break;
            default:
                System.out.println("无此routingKey");
                break;
        }


    }
}
